﻿using Maticsoft.Model;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net;
using System.Text;
using System.Web;
using System.Xml.Linq;

namespace FangChanCrm
{
    public  static class WeiXin_Common
    {
        public static string appid = "wx7e56328944daf763";
        public static string appsecret = "f1b40c412f50213df32e4371086a3400";





        public static string GetUserInfo(string Code,string token)
        {
            //获取微信回传的openid、access token
            string Str = GetJson("https://qyapi.weixin.qq.com/cgi-bin/user/getuserinfo?access_token="+token+"&code="+Code+"");
            //微信回传的数据为Json格式，将Json格式转化成对象
            //OAuth_Token Oauth_Token_Model = JsonHelper.JsonDeserialize<Model.OAuth_Token>(Str);
            return Str;
        }

        public static string Get_access_token()
        {
            //获取微信回传的openid、access token
            string Str = GetJson("https://qyapi.weixin.qq.com/cgi-bin/gettoken?corpid=ww500458ad942a211f&corpsecret=KbQzkn49masS-jKaZzv6NaEFoF_zyM-8f5rXPfjh3mM");
            string d= GetJsonValue(Str, "access_token");
            return d;
        }

        public static string Get_access_token_AQ()
        {
            //获取微信回传的openid、access token
            string Str = GetJson("https://qyapi.weixin.qq.com/cgi-bin/gettoken?corpid=wx5ef8d03d7f89b3c8&corpsecret=EhBdcD59aLgN868HnyxZypyEODfag66IWSM1TCMYM8w");
            string d = GetJsonValue(Str, "access_token");
            return d;
        }


        #region 获取Json字符串某节点的值
        /// <summary>
        /// 获取Json字符串某节点的值
        /// </summary>
        public static string GetJsonValue(string jsonStr, string key)
        {
            string result = string.Empty;
            if (!string.IsNullOrEmpty(jsonStr))
            {
                key = "\"" + key.Trim('"') + "\"";
                int index = jsonStr.IndexOf(key) + key.Length + 1;
                if (index > key.Length + 1)
                {
                    //先截逗号，若是最后一个，截“｝”号，取最小值
                    int end = jsonStr.IndexOf(',', index);
                    if (end == -1)
                    {
                        end = jsonStr.IndexOf('}', index);
                    }

                    result = jsonStr.Substring(index, end - index);
                    result = result.Trim(new char[] { '"', ' ', '\'' }); //过滤引号或空格
                }
            }
            return result;
        }
        #endregion




        public static string Get_UserInfo1(string REFRESH_TOKEN, string OPENID)
        {
            string Str = GetJson("https://api.weixin.qq.com/cgi-bin/user/info?access_token=" + REFRESH_TOKEN + "&openid=" + OPENID);
           
            return Str;
        }



        #region 访问微信url并返回微信信息

        public static string GetJson(string url)
        {
            WebClient wc = new WebClient();
            wc.Credentials = CredentialCache.DefaultCredentials;
            wc.Encoding = Encoding.UTF8;
            string returnText = wc.DownloadString(url);

            if (returnText.Contains("errcode"))
            {
                //可能发生错误
            }
            return returnText;
        }

        #endregion


        /// <summary>  
        /// 根据当前日期 判断Access_Token 是否超期  如果超期返回新的Access_Token   否则返回之前的Access_Token  
        /// </summary>  
        /// <param name="datetime"></param>  
        /// <returns></returns>  
        public static string GetAccess_Token()
        {

            string Token = string.Empty;
            DateTime YouXRQ;
            //// 读取XML文件中的数据，并显示出来 ，注意文件路径  
            //string filepath = HttpContext.Current.Server.MapPath("~/access_token.xml");

            //StreamReader str = new StreamReader(filepath, System.Text.Encoding.UTF8);
            
            XDocument xml = XDocument.Load("wwwroot/access_token.xml");
            //XmlDocument xml = new XmlDocument();
            //xml.Load(str);
            //str.Close();
            //str.Dispose();
            Token = xml.Descendants("Access_Token").FirstOrDefault().Value;
            YouXRQ = Convert.ToDateTime(xml.Descendants("Access_YouXRQ").FirstOrDefault().Value);

            if (DateTime.Now > YouXRQ)
            {
                DateTime _youxrq = DateTime.Now;
                //Access_token mode = GetAccess_token();
                string d = Get_access_token();
                // JObject jo = this.Get_access_token(str_AppID, str_AppSecret);
                xml.Descendants("Access_Token").FirstOrDefault().Value = d;
                _youxrq = _youxrq.AddHours(2);
                xml.Descendants("Access_YouXRQ").FirstOrDefault().Value = _youxrq.ToString();
                Token = d;
            }
            return Token;
        }

    }
}